<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use App\Http\Controllers\Constants;
use JWTAuth;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';
    private $jwtAuth = null;
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
//        $this->jwtAuth = new JWTAuth();
    }

    public function getCode(Request $request) {
        $data = $request->all();
        //如果浏览器显示“图像XXX因其本身有错无法显示”，可尽量去掉文中空格
        //先成生背景，再把生成的验证码放上去
        $img_height=70;//先定义图片的长、宽
        $img_width=25;

        $authnum='';
        //生产验证码字符
        //$ychar="2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z";
        $ychar="1,2,3,4,5,6,7,8,9,0";
        $list=explode(",", $ychar);
        $len = count($list);
        for($i=0; $i<4; $i++){
            $randnum=rand(0, $len - 1);
            $authnum.=$list[$randnum];
        }

        $key = $data['r'];
        $verify_code=MD5(strtolower($authnum));
        Redis::setex($key, 180, $verify_code);

        $aimg = imagecreate($img_height, $img_width);        //生成图片
        imagecolorallocate($aimg, 255,255,255);                //图片底色，ImageColorAllocate第1次定义颜色PHP就认为是底色了
        $black = imagecolorallocate($aimg, 0,0,0);            //定义需要的黑色

        for ($i=1; $i<=100; $i++) {
            imagestring($aimg, 1, mt_rand(1,$img_height), mt_rand(1,$img_width), "@", imagecolorallocate($aimg,mt_rand(200,255), mt_rand(200,255), mt_rand(200,255)));        }

        //为了区别于背景，这里的颜色不超过200，上面的不小于200
        for ($i=0; $i<strlen($authnum); $i++){
            imagestring($aimg, mt_rand(3, 5), $i * $img_height / 4 + mt_rand(2, 7), mt_rand(1, $img_width / 2 - 2), $authnum[$i], imagecolorallocate($aimg, mt_rand(0, 100), mt_rand(0, 150), mt_rand(0, 200)));
        }

        imagerectangle($aimg, 0, 0, $img_height-1, $img_width-1, $black);//画一个矩形
        header("Cache-Control: max-age=1, s-maxage=1, no-cache, must-revalidate");
        header("Content-type: image/PNG");
        imagepng($aimg);                    //生成png格式
        imagedestroy($aimg);
        exit();
    }

    public function login()
    {
        $dataJson = json_decode(file_get_contents("php://input"), true);

        $validator=Validator::make($dataJson,[
            'user_login_name'=>'required',
            'verify_code'=>'required',
            'pwd'=>'required',
            'r'=>'required'
        ]);
        if ($validator->fails()) {
            $errmsg = null;
            $errors = $validator->errors()->all();

            foreach ($errors as $errorValue) {
                $errmsg .= $errorValue;
            }

            $this->returnData(false, $errmsg, null);
        }

        $userName = $dataJson['user_login_name'];
        $password = $dataJson['pwd'];

        $code = MD5(strtolower($dataJson['verify_code']));
        $verify_code = Redis::get($dataJson['r']);

        if ($code !== $verify_code) {
            $this->returnData(false, '验证码错误', '');
        }

        $user = User::where('user_login_name', $userName)->first();
        if (empty($user)) {
            $this->returnData(false, '用户名不存在');
        }
        if (!Hash::check($password, $user['pwd'])) {
            $this->returnData(false, '密码错误');
        }
        if (intval($user['status']) !== 2) {
            $this->returnData(false, '该用户已禁用');
        }

        Redis::del($dataJson['r']);

        $admin_user = array(
            'user_id' => $user['id'],
            'username' => $user['user_login_name'],
        );
        $token = JWTAuth::fromUser($user);
        Redis::setex($token, Constants::LOGIN_REDIS_EXPIRE, serialize($admin_user));
        setcookie('_token', $token, Constants::LOGIN_REDIS_EXPIRE, '/');

        $this->returnData(true, '登录成功', $admin_user);
    }

    public function logout() {
        $res = Redis::del($_COOKIE['_token']);
        if ($res!= 1) {
            $this->returnData(false, '登出失败或者已经登出', '');
        }

        $this->returnData(true, '登出成功', '');
    }
}
